<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        .item{
            float: left;
            border: 1px solid #eee;
        }
        .item img{
            width: 240px;
            vertical-align: bottom;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div id="app"></div>
    <script>
        http();

        $(window).scroll(function(){
            // console.log(isReachBottom())
            if(isReachBottom()){
                http()
            }
        })
/*  */
        function http(){
            var url = "http://192.168.4.18:8000/more";
        $.ajax({
            url,
            success:res=>{
            // console.log(res)
            // var arr = res.result;
            
                res.forEach(item=>{
                
                    // console.log(arr)
                    var htmlItem = `
                    <div class="item">
                        <img src=${item.imageUrl} alt="">
                        
                    </div>
                    `
                    $("#app").append(htmlItem) 
                })
                    setTimeout(sortBox,100)
                    sortBox();
            }
        })
        }
        
/*  */

        function isReachBottom(){
            var scrollTop = $(window).scrollTop();
            var availHeight = $(window).height();
            var dh = $(document).height();
            return (scrollTop+availHeight>dh-200)?true:false;
        }

/*  */
        function sortBox(){
            /* 1.获取一排能放几个盒子 */
            var  ww =  $(window).width();
            var box =  $(".item").outerWidth();
            var num =  Math.floor(ww/box);
            var  arr = [] 
            /* 2.将第一排的高度放在一个数组中 */
            $(".item").each((index,value)=>{
                if(index<num){
                    var height = $(value).outerHeight();
                    arr.push(height)
                }else{
                    /* 3.从高度最小的地方放置图片 */
                    var minHeight = Math.min(...arr);
                    var index= arr.indexOf(minHeight);
                    var offsetLeft = $(".item").eq(index).offset().left;
                    $(value).css({position:"absolute",left:offsetLeft,top:minHeight})
                    arr[index] = minHeight+ $(value).outerHeight();
                }
            })
            }
        
    </script>
</body>
</html>